package cc.rengu.igas.channel.wechat.core.packswitch;

import cc.rengu.igas.channel.wechat.common.constant.WechatParamConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatTreeNodeConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatTxnNumConstant;
import cc.rengu.jradp.packetswitch.IncomingPackSwitchImpl;
import cc.rengu.jradp.packetswitch.OutgoingPackSwitchImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.RandomUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

/**
 * 与微信通讯层报文解包前后、组前包后实现类
 * Created by 王成 on 2018/5/31.
 */
public class WechatRefundNotifyPackSwitch implements IncomingPackSwitchImpl, OutgoingPackSwitchImpl {


    @Override
    public byte[] beforeInComPackSwitch(byte[] bytes) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String message = new String(bytes);
        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.MESSAGE, message);
        return bytes;
    }

    @Override
    public int afterInComPackSwitch() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.INST_ID, AppParamConstant.DEFAULT_INSTID);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.MSG_SRC_ID, WechatParamConstant.TUNL_ID_WXZF);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.BIZ_TYPE, AppParamConstant.DEFAULT_BIZ_TYPE);
        xmlTreeUtil.setXmlTreeStringValue(AppParamConstant.SYS_ID, WechatParamConstant.TUNL_ID_WXZF);
        if (xmlTreeUtil.isExist(WechatTreeNodeConstant.WX_ORDER_ID)) {
            xmlTreeUtil.copyStringValue(WechatTreeNodeConstant.WX_ORDER_ID, TreeNodeConstant.FRONT_SEQ_NUM);
        } else {
            String frontSeqNum = WechatParamConstant.PREFIX_SEQ_STRING + DateUtil.getCurrentDate() + DateUtil.getCurrentTime() + RandomUtil.getRandomInt();
            xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.FRONT_SEQ_NUM, frontSeqNum);
        }
        /* 重置微信退款交易通知码 */
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, WechatTxnNumConstant.T00CH200);
        return 0;
    }

    @Override
    public int beforeOutgoPackSwitch() throws Exception {
        return 0;
    }

    @Override
    public byte[] afterOutgoPackSwitch(byte[] bytes) throws Exception {
        return bytes;
    }
}
